home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11686 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: anvil.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: String Problem
  5. Date: 25 Mar 1996 11:20:39 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4j6rm7INNge5@anvil.ugrad.cs.ubc.ca>
  8. References: <4j6l61$4no@B1FF.mindspring.com>
  9. NNTP-Posting-Host: anvil.ugrad.cs.ubc.ca
  10.  
  11. In article <4j6l61$4no@B1FF.mindspring.com>,
  12. Shon Frazier <vtipres@atl.mindspring.com> wrote:
  13.  >This is supposed to be a variation on sample code from a textbook.
  14.  >Can anyone tell me why NameCheck = 0 when I run the program?
  15.  >
  16.  >/*
  17.  >   Testing character transactions.
  18.  >*/
  19.  >
  20.  >#include <stdio.h>
  21.  >#include <ctype.h>
  22.  >
  23.  >int main()
  24.  >{
  25.  >   char Name[11] = "John";
  26.  >   char *WhereName;
  27.  >   int NameCheck = 0;
  28.  >
  29.  >   WhereName = Name;
  30.  >
  31.  >   if ( WhereName == "John" )
  32.  >   {
  33.  >      NameCheck = 1;
  34.  >   }
  35.  >
  36.  >   printf( "Name: %s\n", Name );
  37.  >   printf( "NameCheck = %i\n", NameCheck );
  38.  >   printf( "WhereName = %i\n", WhereName );
  39.  >}
  40.  >
  41.  >
  42.  
  43. NameCheck is zero after you run the program because the pointer WhereName does
  44. not coincide with the address of the string literal "John".
  45.  
  46. You have pointed WhereName to be the address of the automatic object Name[0],
  47. that is, a pointer to the first element of Name. 
  48.  
  49. Then in your if statement, you compare this pointer against the string literal,
  50. which has a unique address distinct from Name, hence the comparison fails.
  51.  
  52. You are comparing two character pointer values, not two strings.
  53.  
  54. To compare the actual string data, include <string.h> and use the function
  55. called strcmp(). The == operator is not overloaded in C to compare strings.
  56. -- 
  57.  
  58.